package com.york.jobmew.subject.application.interceptor;

import com.york.jobmew.subject.common.constants.LoginConstant;
import com.york.jobmew.subject.common.context.LoginContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * 拦截器的执行在过滤器之后，过滤器在请求达到servlet前执行，拦截器是进入controller前的处理
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 前置处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String loginId = request.getHeader(LoginConstant.LOGIN_ID);
        if (StringUtils.isNotBlank(loginId)) {
            LoginContextHolder.set(LoginConstant.LOGIN_ID, loginId);
        }
        return true;
    }

    /**
     * 后置处理
     * 这里为了防止内存泄露以及多线程复用时上下文不一致的情况，必须remove
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        LoginContextHolder.remove();
    }

}
